import { DataTypes } from "sequelize";
import { BadRequestError } from "../utils/errors.js";

export default function initUser (sequelize) {
  const User = sequelize.define(
    "User",
    {
      id: {
        type: DataTypes.UUID,
        primaryKey: true,
        defaultValue: DataTypes.UUIDV4,
        comment: "用户唯一ID"
      },
      username: {
        type: DataTypes.STRING(50),
        allowNull: false,
        unique: true,
        comment: "用户名",
        validate: {
          len: [3, 50],
          is: /^[a-zA-Z0-9_]+$/
        },
        set(value) {
          this.setDataValue('username', value.toLowerCase());
        }
      },
      password: {
        type: DataTypes.STRING(100),
        allowNull: false,
        comment: "加密后的密码",
        validate: {
          len: [8, 100]
        }
      },
      email: {
        type: DataTypes.STRING(100),
        allowNull: true,
        unique: true,
        comment: "电子邮箱",
        validate: {
          isEmail: true
        },
        set(value) {
          if (value) {
            this.setDataValue('email', value.toLowerCase());
          }
        }
      },
      phone: {
        type: DataTypes.STRING(20),
        allowNull: true,
        unique: true,
        comment: "手机号码",
        validate: {
          is: /^1[3-9]\d{9}$/
        }
      },
      avatar: {
        type: DataTypes.STRING(512),
        allowNull: true,
        comment: "头像URL"
      },
      nickname: {
        type: DataTypes.STRING(50),
        allowNull: true,
        comment: "用户昵称",
        validate: {
          len: [2, 50]
        }
      },
      role: {
        type: DataTypes.ENUM("user", "admin", "editor", "superadmin"),
        defaultValue: "user",
        comment: "用户角色"
      },
      status: {
        type: DataTypes.ENUM("active", "inactive", "banned", "pending"),
        defaultValue: "pending",
        comment: "账户状态"
      },
      last_login: {
        type: DataTypes.DATE,
        allowNull: true,
        comment: "最后登录时间"
      },
      login_attempts: {
        type: DataTypes.INTEGER,
        defaultValue: 0,
        comment: "登录尝试次数"
      },
      refresh_token: {
        type: DataTypes.STRING(500),
        allowNull: true,
        comment: "刷新令牌"
      },
      email_verified: {
        type: DataTypes.BOOLEAN,
        defaultValue: false,
        comment: "邮箱是否验证"
      },
      phone_verified: {
        type: DataTypes.BOOLEAN,
        defaultValue: false,
        comment: "手机是否验证"
      }
    },
    {
      tableName: "users",
      timestamps: true,
      paranoid: true,
      indexes: [
        { fields: ["username"] },
        { fields: ["email"] },
        { fields: ["phone"] },
        { fields: ["role"] },
        { fields: ["status"] }
      ],
      hooks: {
        beforeSave: async (user) => {
          if (user.changed("password")) {
            try {
              user.password = await bcrypt.hash(user.password, 12);
            } catch (error) {
              throw new BadRequestError("密码加密失败");
            }
          }
        },
        afterCreate: (user) => {
          if (!user.nickname) {
            user.update({ nickname: `用户${user.id.slice(0, 8)}` });
          }
        }
      }
    }
  );

  // 实例方法：验证密码
  User.prototype.comparePassword = async function (candidatePassword) {
    return await bcrypt.compare(candidatePassword, this.password);
  };

  // 实例方法：获取公开用户信息
  User.prototype.getPublicProfile = function () {
    return {
      id: this.id,
      username: this.username,
      nickname: this.nickname,
      avatar: this.avatar,
      role: this.role,
      status: this.status,
      createdAt: this.createdAt
    };
  };

  // 类方法：通过用户名查找用户
  User.findByUsername = async function (username) {
    return await this.findOne({
      where: { username: username.toLowerCase() }
    });
  };

  // 类方法：验证用户凭证
  User.verifyCredentials = async function (identifier, password) {
    const user = await this.findOne({
      where: {
        [DataTypes.Op.or]: [
          { username: identifier.toLowerCase() },
          { email: identifier.toLowerCase() },
          { phone: identifier }
        ]
      }
    });

    if (!user) {
      throw new BadRequestError("用户不存在");
    }

    if (user.status !== "active") {
      throw new BadRequestError("账户未激活或已被禁用");
    }

    const isMatch = await user.comparePassword(password);
    if (!isMatch) {
      throw new BadRequestError("密码错误");
    }

    return user;
  };

  return User;
};